import GpContainer from "@/components/GpContainer";
import GpFontIcon from "@/components/GpFontIcon";
import GpNavbar from "@/components/GpNavbar";
import { GpTouchableView } from "@/components/GpTouchableView";
import { useNavigationOpacity } from "@/hooks/useNavigationOpacity";
import { noop } from "@/utils/helper";
import { SafeArea } from "@taroify/core";
import { Image, Map, type MapProps, Text, View } from "@tarojs/components";
import clsx from "clsx";
import Taro, { useRouter } from "@tarojs/taro";
import { useEffect, useMemo, useRef } from "react";
import { useImmer } from "use-immer";
import { getMychatViewinterviewInterviewId, postMychatExecutecardactionId } from "@/apis/endpoint/myChat";
import { EnumInterviewState, EnumMyChatCardAction, InterviewResult } from "@/apis/endpoint/model";
import { bd09togcj02 } from "@/utils/coor-transform";
import { navigate } from "@/utils/navigation";
import { pageMapper } from "@/constants/pageMap";
import { useNavigateEventChannel } from "@/hooks/useNavigateEventChannel";
import { dateUtil } from "@/utils/date";

interface RouteParams extends Recordable {
  id: string
  messageId?: string
}
export default function Index() {
  const [opacity] = useNavigationOpacity()
  const { eventChannel } = useNavigateEventChannel()
  const params = useRouter<RouteParams>().params
  const [detail, setDetail] = useImmer({} as InterviewResult)
  const [location, setLocation] = useImmer<{markers: MapProps.marker[]; at: {longitude: number; latitude: number;}}>({
    markers: [
      {
        id: 1,
        longitude: 113.324520,
        latitude: 23.099994,
        iconPath: "/static/icons/common/map-marker.png",
        width: 24,
        height: 24
      }
    ],
    at: {
      longitude: 113.324520,
      latitude: 23.099994,
    }
  })
  const timer = useRef<INullable<NodeJS.Timeout>>(null)
  const [timeLeft, setTimeLeft] = useImmer({ hours: 0, minites: 0 })
  const stateDispaly = useMemo(() => {
    let text = "面试邀请"
    if (detail.state === EnumInterviewState.不通过) {
      text = "面试不通过"
    } else if (detail.state === EnumInterviewState.取消) {
      text = "面试已取消"
    } else if (detail.state === EnumInterviewState.已通过) {
      text = "面试已通过"
    } else if (detail.state === EnumInterviewState.待定) {
      text = "已面试"
    } else if (detail.state === EnumInterviewState.待接受) {
      text = "面试待接受"
    } else if (detail.state === EnumInterviewState.待面试) {
      text = `${timeLeft.hours}小时${timeLeft.minites}分钟后面试`
    }
    return text
  }, [detail, timeLeft])
  const showActions = useMemo(() => {
    return detail.state === EnumInterviewState.待接受
  }, [detail])
  useEffect(() => {
    fetchDetail()
    return endTimer
  }, [])
  function endTimer() {
    if (timer.current) clearTimeout(timer.current)
  }
  function startTimer(info: InterviewResult) {
    if (info.state === EnumInterviewState.待面试) {
      endTimer()
      const future = dateUtil(info.interviewTime)
      const now = dateUtil()
      function action() {
        let minutes = future.diff(now, "minute")
        const hours = Math.floor(minutes / 60)
        minutes = minutes - hours * 60
        setTimeLeft(draft => {
          draft.hours = hours
          draft.minites = minutes
        })
        timer.current = setTimeout(action, 1000 * 60)
      }
      timer.current = setTimeout(action, 1000 * 60)
      action()
    }
  }
  function fetchDetail() {
    getMychatViewinterviewInterviewId(Number(params.id)).send()
    .then(detail => {
      setDetail(detail)
      if (detail.jobAddress && detail.jobAddress.lat && detail.jobAddress.lng) {
        const [longitude, latitude] = bd09togcj02(detail.jobAddress.lng!, detail.jobAddress.lat!)
        setLocation(draft => {
          draft.at.longitude = longitude
          draft.at.latitude = latitude
          draft.markers[0].longitude = longitude
          draft.markers[0].latitude = latitude
          draft.markers[0].callout = {
            content: detail.jobAddress.fullAddress!,
            bgColor: "#ffffff",
            borderRadius: 8,
            color: "#313337",
            display: "ALWAYS",
            fontSize: 14,
            padding: 12,
            anchorX: 0,
            anchorY: 0,
            borderColor: "#ffffff",
            borderWidth: 0,
            textAlign: "center"
          }
        })
      }
      startTimer(detail)
    })
  }
  async function handleReject() {
    const { confirm } = await Taro.showModal({
      content: "确定拒绝当前公司的面试邀请？",
      cancelText: "关闭",
      confirmText: "确认",
      confirmColor: "#0768FA",
    })
    if (confirm) {
      const nextMessageId = await postMychatExecutecardactionId(detail.chatId, {
        action: EnumMyChatCardAction.求职者拒绝面试邀请,
        chatMsgId: Number(params.messageId!)
      }).send()
      Taro.showToast({
        title: '面试已拒绝',
        icon: 'none'
      })
      if (nextMessageId && eventChannel) {
        eventChannel.emit("action", {type: "reject", messageId: Number(params.messageId), nextMessageId, chatId: detail.chatId})
      }
      navigate()
    }
  }
  async function handleAccept() {
    const nextMessageId = await postMychatExecutecardactionId(detail.chatId, {
      action: EnumMyChatCardAction.求职者同意面试邀请,
      chatMsgId: Number(params.messageId!)
    }).send()
    Taro.showToast({
      title: '面试已接受',
      icon: 'none'
    })
    if (nextMessageId && eventChannel) {
      eventChannel.emit("action", {type: "agreen", messageId: Number(params.messageId), nextMessageId, chatId: detail.chatId})
    }
    fetchDetail()
  }
  return <GpContainer className="bg-white">
    <GpNavbar
      navigationBarTitleText="面试邀请"
      navigationBarPlaceholder={false}
      navigationBarBackgroundColor={`rgba(255, 255, 255, ${opacity})`}
    />
    <View className="relative w-full h-[400px] box-border">
      <Image src="/static/images/common/home-bg.png" className="w-full absolute left-0 top-0 z-0" mode="widthFix" />
      <View className="absolute inset-0">
        <View className="absolute left-0 right-0 bottom-0 px-[48px] pb-[48px]">
          <View className="text-[48px] !leading-[48px] text-[#324366] font-bold">
            {stateDispaly}
          </View>
          <View className="text-[28px] !leading-[36px] text-secondary mt-[24px]">
            {
              detail.state === EnumInterviewState.待面试
              ? "接受面试后，自动交换电话；如已投递简历，面试人员可查看"
              : "面试请加油！全力以赴，以平和心态面对接下来的挑战吧！"
            }
          </View>
        </View>
      </View>
    </View>
    <View className={clsx("box-border -mt-[16px]", { "pb-[144px]": showActions })}>
      <View className="rounded-t-[48px] bg-white overflow-hidden shadow-[0_4px_40px_rgba(46,41,77,0.06)] px-[48px] py-[8px]">
        <View className="flex flex-row items-center gap-[24px] py-[40px]">
          <Image src={detail.companyLogo || __DEF_COMPANY_LOGO__} className="size-[112px] object-cover flex-none" />
          <View className="box-border">
            <View className="text-primary text-[36px] !leading-[44px] font-bold">{detail.companyName}</View>
            <View className="flex flex-row items-center mt-[16px]">
              <Image src={detail.interviewUserAvatar || __DEF_AVATAR__} className="size-[40px] object-cover rounded-[50%] mr-[12px]" />
              <View className="text-secondary text-[28px] !leading-[28px] mr-[8px]">{detail.interviewUserName}</View>
              <View className="text-secondary text-[28px] !leading-[28px]">向你发来面试邀请</View>
            </View>
          </View>
        </View>
        <View className="py-[40px] border-t border-solid border-t-[#EEEEEE]">
          <View className="text-third text-[28px] !leading-[28px]">面试职位</View>
          <View className="mt-[20px] flex flex-row justify-between items-center">
            <View className="text-primary text-[28px] !leading-[28px] font-bold">{detail.jobName}</View>
            <GpFontIcon name="icon-a-jiantou_youda" size={40} color="#707275" onClick={() => {
              navigate(pageMapper.position.job, {id: detail.jobId})
            }} />
          </View>
        </View>
        <View className="py-[40px] border-t border-solid border-t-[#EEEEEE]">
          <View className="text-third text-[28px] !leading-[28px]">面试时间</View>
          <View className="text-primary text-[28px] !leading-[28px] font-bold mt-[20px]">{detail.interviewTimeString}</View>
        </View>
        <View className="py-[40px] border-t border-solid border-t-[#EEEEEE]">
          <View className="text-third text-[28px] !leading-[28px]">联系人</View>
          <View className="mt-[20px] flex flex-row justify-between items-center">
            <View className="text-primary text-[28px] !leading-[28px] font-bold">{detail.interviewUserName}</View>
            <GpTouchableView className="px-[24px] h-[48px] flex flex-row items-center gap-[8px] rounded-[48px] border-2 border-solid border-theme/60" onClick={() => {
              Taro.makePhoneCall({
                phoneNumber: detail.interviewUserMobile!
              })
            }}>
              <GpFontIcon name="icon-ic_shouji" size={24} className="text-theme/60"/>
              <Text className="text-[24px] text-theme">打电话</Text>
            </GpTouchableView>
          </View>
        </View>
        <View className="py-[40px] border-t border-solid border-t-[#EEEEEE]">
          <View className="text-third text-[28px] !leading-[28px]">面试地点</View>
          <View className="h-[240px] box-border mt-[20px]">
            <Map
              id="interview-map"
              style="width: 100%; height: 100%;"
              longitude={location.at.longitude}
              latitude={location.at.latitude}
              scale={14}
              markers={location.markers}
              onError={noop}
            />
          </View>
        </View>
        <View className="py-[40px] border-t border-solid border-t-[#EEEEEE]">
          <View className="text-third text-[28px] !leading-[28px]">备注</View>
          <View className={clsx("text-[28px] !leading-[28px] font-bold mt-[20px]", detail.note ? "text-primary" : "text-placeholder")}>
            {detail.note || "暂无备注"}
          </View>
        </View>
      </View>
    </View>
    {
      showActions && (
        <View className="fixed left-0 right-0 bottom-0 box-border bg-white">
          <View className="flex flex-row gap-[20px] items-center justify-center h-[144px]">
            <GpTouchableView onClick={handleReject} className="flex flex-row justify-center items-center rounded-[40px] text-[28px] h-[80px] w-[240px] bg-[#313337]/10 text-primary">
              拒绝面试
            </GpTouchableView>
            <GpTouchableView onClick={handleAccept} className="flex flex-row justify-center items-center rounded-[40px] text-[28px] h-[80px] w-[426px] bg-theme text-white">
              接受面试
            </GpTouchableView>
          </View>
          <SafeArea position="bottom" />
        </View>
      )
    }
  </GpContainer>
}
